<template>
	<div>
		<!-- 头部查询框 -->
		<el-form ref="searchForm" :inline="true" :model="searchMap" style="margin-top: 20px;" >
			<el-form-item prop="phone">
				<el-input v-model="searchMap.name" placeholder="角色名搜索" style="width: 200px;" ></el-input>
			</el-form-item>
			<el-form-item prop="name">
				<el-input v-model="searchMap.tips" placeholder="标签搜索" style="width: 200px;" ></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" @click="getList()">查询</el-button>
				<el-button @click="restForm('searchForm')">重置</el-button>
				<el-button type="infor" icon="el-icon-key" @click="admin()">权限分配</el-button>
			</el-form-item>
		</el-form>
		<!-- 表格数据 -->
	  <el-table
		:data="tableData"
		style="width: 100%"
		:default-sort = "{prop: 'date', order: 'descending'}"
		@selection-change="getSelection"
		>
		<el-table-column
		  type="selection"
		  width="55">
		</el-table-column><el-table-column prop="name" label="角色名" sortable>
		</el-table-column><el-table-column prop="tips" label="标签" sortable>
		</el-table-column>
		<el-table-column
		  align="right">
		  <template slot="header" slot-scope="scope">
				<el-button type="success" icon="el-icon-plus" circle @click="add"></el-button>
				<el-button type="danger" icon="el-icon-delete" circle @click="del"></el-button>
		  </template>
		  <template slot-scope="scope">
			<el-button
			  size="mini" round
			  type="warning"
			  @click="handleEdit(scope.row.pk)">编辑</el-button>
		  </template>
		</el-table-column>
	  </el-table>
	  <!-- 分页，添加在div里面 -->
		<!-- <el-pagination
		@size-change="handleSizeChange"
		@current-change="handleCurrentChange"
		:current-page="currentPage"
		:page-sizes="[10, 20, 50,100,300,500,1000]"
		:page-size="pageSize"
		layout="total, sizes, prev, pager, next, jumper"
		:total="total">
		</el-pagination> -->
		<!-- 对话框 -->
		<!-- 分页组件 -->
		<Page :pageMessage="searchMap" :totalCounts="total" @fathermethod="getList"></Page>
		<!-- 抽屉框 -->
		<el-drawer
		  title="用户信息"
		  :before-close="handleClose"
		  :visible.sync="dialog"
		  direction="rtl"
		  custom-class="demo-drawer"
		  ref="drawer"
		  size="40%"
		  >
		  <div class="demo-drawer__content">
			<el-form :inline="true" class="demo-ruleForm" label-width="150px" >
			  <el-form-item label="角色名">
				<el-input v-model="form.name" placeholder="请输入文本" class="inputWidth"></el-input>
			  </el-form-item>
			</el-form>
			<el-form :inline="true" class="demo-form-inline" label-width="150px" >
			  <el-form-item label="标签">
				<el-input v-model="form.tips" placeholder="请输入文本" class="inputWidth"></el-input>
			  </el-form-item>
			</el-form>
			<div class="demo-drawer__footer">
			  <el-button @click="dialog = false">取 消</el-button>
			  <el-button type="primary" @click="save">保存</el-button>
			</div>
		  </div>
		</el-drawer>
		<!-- 抽屉框 -->
		<el-drawer
		  title="权限分配"
		  :before-close="handleClose2"
		  :visible.sync="dialog2"
		  direction="rtl"
		  custom-class="demo-drawer"
		  ref="drawer"
		  size="50%"
		  >
		  <div class="demo-drawer__content">
			<el-tree
			  :data="treeData"
			  :props="defaultProps"
			  show-checkbox
			  check-strictly=true
			  node-key="pk" 
			  ref="tree"
			  @node-click="onclick"
			  @check-change="handleCheckChange">
			</el-tree>
			<div class="demo-drawer__footer">
			  <el-button @click="dialog2 = false">取 消</el-button>
			  <el-button type="success" @click="resetChecked">清空</el-button>
			  <el-button type="primary" @click="saveAdmin">保存</el-button>
			</div>
		  </div>
		</el-drawer>
	</div>
</template>

<script>
  import Page from "@/components/common/pageHapler.vue"
  export default {
    data() {
      return {
		parentPk:"0",
		treePk:"",
		defaultProps: {
			pk:"pk",
            children: 'children',
            label: 'label'
        },
		treeData: [{
          label: '一级 1',
			children: [{
				label: '二级 1-1',
				children: [{
				  label: '三级 1-1-1'
				}],
			}]
        }],
		pks:'',
		form: {
		},
		dialog:false,
		dialog2:false,
		formLabelWidth: '150px',
		loading: false,
		total: 50, // 总记录数
		//: 1, // 当前页, 默认第1页
		//pageSize: 2, // 每页显示条数， 10条
		searchMap: {
			name: '',
			phone: '',
			currentPage:1,
			pageSize:10
		}, // 条件查询
        tableData: [],
      }
    },
    methods: {
		formatter(row, column) {
			return row.sex==1?'男':'女';
		},
		/* handleSizeChange(val) {
			this.searchMap.pageSize = val
			this.getList()
		},
		handleCurrentChange(val) {
			this.searchMap.currentPage = val
			this.getList()
		}, */
		// 表单重置，
		// 在 el-form-item 标签属性 prop 上, 指定了字段名, 重置才会生效
		restForm(formName) {
			this.$refs[formName].resetFields();
		},
		add(){//新增
			this.dialog = true
			this.form={}
			/* this.$nextTick(() => {
			// this.$nextTick()它是一个异步事件，当渲染结束 之后 ，它的回调函数才会被执行
			// 弹出窗口打开之后 ，需要加载Dom, 就需要花费一点时间，我们就应该等待它加载完dom之后，再进行调
			//用resetFields方法，重置表单和清除样式
			this.$refs['form'].resetFields()
			}) */
		},
		handleEdit(pk){//编辑
			this.dialog=true
			this.getDetail(pk);
		},
		del(){//删除
			if(this.pks==''){
				this.$message.error('请选中要删除项');
			}else{
				this.$confirm('确定要删除吗, 是否继续?', '提示', {
				  confirmButtonText: '确定',
				  cancelButtonText: '取消',
				  type: 'warning'
				}).then(() => {
					this.getAxios("sysRole/delete/"+this.pks).then(resp=>{
						console.log(resp)
						if(resp.code==200){
							this.getList();
						}else{
							this.$message.error(resp.message);
						}
					})
				}).catch(() => {
				  this.$message({
					type: 'info',
					message: '已取消删除'
				  });          
				});
			}
		},
		save(){//保存角色
			this.postAxios("sysRole/save",{jsonstr:JSON.stringify(this.form)}).then(resp=>{
				if(resp.code==200){
					this.$message.success(resp.message);
					this.dialog=false;
					this.getList();
				}else{
					this.$message.error(resp.message);
				}
			})
		},
		getSelection(selection){//获取选中的pk
			var pks = "";
			for (var i = 0; i < selection.length; i++) {
				pks+=selection[i].pk
				if(i!=selection.length-1){
					pks+=",";
				}
			}
			this.pks=pks;
		},
		handleClose(done) {//关闭弹出框
			this.dialog=false
		},
		handleClose2(done){
			this.dialog2=false
		},
		getList(val,num){//获取首页列表数据
			if(val!=""&&num==1){
				this.searchMap.pageSize=val
			}
			if(val!=""&&num==2){
				this.searchMap.currentPage=val
			}
			this.postAxios("sysRole/list",{str:JSON.stringify(this.searchMap)}).then(resp=>{
				if(resp.code==200){
					this.tableData=resp.data.list;
					this.total=resp.data.total;
				}else{
					this.$message.error(resp.message);
				}
			})
		},
		getDetail(pk){//获取详情
			this.getAxios("sysRole/query/"+pk).then(resp=>{
				if(resp.code==200){
					this.form=resp.data;
				}else{
					this.$message.error(resp.message);
				}
			})
		},
		handleCheckChange(data, checked, indeterminate) {
			//console.log(data, checked, indeterminate);
		},
	    onclick(data) {
			console.log(data)
			this.parentPk=data.pk
	    },
		getCheckedKeys() {//获取复选框选中的pk数组
			return this.$refs.tree.getCheckedKeys();
        },
		setCheckedKeys(list) {//设置哪些是被选中的复选框
			this.$refs.tree.setCheckedKeys(list);
        },
        resetChecked() {//重置复选框
			this.$refs.tree.setCheckedKeys([]);
        },
		/* loadNode(node, resolve) {
			var pcode="0"
			if(node.level>0){
				pcode=node.data.pk;
			}
			this.getAxios("sysRole/getMenuTree?pcode="+pcode).then(resp=>{
			    if(resp.code==200){
				   return resolve(resp.data);
			    }
			})
        }, */
		admin(){//权限分配
			if(this.pks==""){
				this.$message.error("您尚未选中项");
				return
			}
			if(this.pks.split(",").length>1){
				this.$message.error("只能选中一项");
				return;
			}
			this.dialog2=true;
			this.getTreeList();
			this.getAxios("sysRelation/getMenuPks?rolePk="+this.pks).then(resp=>{
				if(resp.code==200){
					this.setCheckedKeys(resp.data);
				}
			})
		},
		getTreeList(){
			this.getAxios("sysRole/getMenuTree?pcode="+this.parentPk).then(resp=>{
			    if(resp.code==200){
				   this.treeData=resp.data;
			    }
			})
		},
		saveAdmin(){//保存权限
			const sysRelationList=[];
			const menuList=this.getCheckedKeys();
			if(menuList==""){
				const sysRelation={};
				sysRelation.rolePk=this.pks;
				sysRelationList.push(sysRelation);
			}else{
				for (var i = 0; i < menuList.length; i++) {
					const sysRelation={};
					sysRelation.rolePk=this.pks;
					sysRelation.menuPk=menuList[i];
					sysRelationList.push(sysRelation);
				}
			}
			this.postAxios("sysRelation/save",{str:JSON.stringify(sysRelationList)}).then(resp=>{
				if(resp.code==200){
					this.dialog2=false;
				}
			})
		}
    },
	mounted(){
		this.getList();
	},
	components:{
		Page
	}
  }
</script>
<style scoped>
	.demo-drawer__content{
		padding: 20px;
	}
	.demo-drawer__footer{
		text-align: center;
	}
	.inputWidth{
		width: 300px;
	}
	.el-drawer__header{
		text-align: center;
	}
</style>